package com.caigou.service.impl;

import com.caigou.bean.cms.entity.AudioFolder;
import com.caigou.bean.cms.entity.Audio;
import com.caigou.bean.cms.param.*;
import com.caigou.bean.exam.entity.Users;
import com.caigou.component.OSSComponent;
import com.caigou.constant.NewsConstant;
import com.caigou.enums.AudioEnum;
import com.caigou.enums.FailResultEnum;
import com.caigou.enums.SuccessResultEnum;
import com.caigou.mapper.cms.AudioFolderMapper;
import com.caigou.mapper.cms.AudioMapper;
import com.caigou.service.AudioService;
import com.caigou.util.FileUtil;
import com.caigou.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;

import org.springframework.aop.framework.AopContext;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("audioService")
public class AudioServiceImpl implements AudioService {
    @Resource
    private AudioFolderMapper audioFolderMapper;

    @Resource
    private AudioMapper audioMapper;

    @Resource
    private OSSComponent ossComponent;

    /**
     * 获取音频库根文件夹
     * @return
     */
    public AudioFolder getRootAudioFolder(){
        return audioFolderMapper.getRootAudioFolder();
    }

    /**
     * 创建音频库文件夹
     * @param superId
     * @param folderName
     * @param userId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Throwable.class)
    public Result createAudioFolder(Integer superId, String folderName, String userId){
        //获取父文件夹
        AudioFolder parent = audioFolderMapper.selectByPrimaryKey(superId);
        if(parent==null){
            return Result.error("音频库父文件夹不存在");
        }
        //获取父文件夹信息
        Integer parentLevel = parent.getLevel();
        String parentPath = parent.getPath();
        if(parentLevel<1){
            log.warn("音频父目录级别level错误，leve值应该大于0，实际level={}", parentLevel);
            return Result.error("音频库父文件夹级别错误");
        }
        //保存本级文件夹信息
        AudioFolder audioFolder = new AudioFolder();
        long timestamp = System.currentTimeMillis();
        Date current = new Date(timestamp);
        audioFolder.setCreateTime(current);
        audioFolder.setUpdateTime(current);
        audioFolder.setFolderName(folderName);
        audioFolder.setHasSubfolder(0);
        audioFolder.setCreateUserId(userId);
        audioFolder.setUpdateUserId(userId);
        audioFolder.setLevel(parentLevel+1);
        audioFolder.setSuperId(superId);
        int scount = 0;
        try{
            scount = this.saveAudioFolder(audioFolder);
        }catch(DataAccessException e){
            log.error(e.getMessage(), e);
            return Result.custom(400, "创建文件夹名称重复", "创建文件夹名称重复");
        }

        //更新本级文件夹path
        Integer folderId = audioFolder.getId();
        String path = parentPath+folderId+"/";
        audioFolder.setPath(path);
        audioFolder.setUpdateTime(new Date(System.currentTimeMillis()));
        int ucount = audioFolderMapper.updatePath(audioFolder);
        log.info("保存音频文件夹结果={}， 更新音频文件夹结果={}, id={}，userId={}", scount, ucount, folderId, userId);

        //更新父级文件夹hashSubfolder
        if(parent.getHasSubfolder().intValue()==0){//父级文件夹没有子文件夹
            parent.setHasSubfolder(1);
            parent.setUpdateTime(new Date(System.currentTimeMillis()));
            int count = audioFolderMapper.updateHasSubfolder(parent);
            log.info("更新父级音频文件夹hasSubfolder结果={}，id={}", count, parent.getId());
        }
        return Result.success("用户创建音频库文件夹成功");
    }

    public int saveAudioFolder(AudioFolder audioFolder){
        return audioFolderMapper.insertSelective(audioFolder);
    }

    public List<AudioFolder> listAudioFolderBySuperId(Integer superId){
        return audioFolderMapper.listAudioFolderBySuperId(superId);
    }

    /**
     * 删除音频库文件夹，实际是逻辑删除
     * @param id 音频库文件夹id
     * @return
     */
    public Result deleteAudioFolder(Integer id){
        AudioFolder audioFolder = audioFolderMapper.selectByPrimaryKey(id);
        //判断是否默认文件夹
        if(audioFolder.getIsDefaultFolder()==1){
            return Result.error(FailResultEnum.AUDIO_FOLDER_ERROR, "音频文件夹为默认文件夹，不能删除");
        }
        //判断是否有子文件夹
        if(audioFolder.getHasSubfolder()==1){
            return Result.error(FailResultEnum.AUDIO_FOLDER_ERROR, "音频文件夹有子文件夹，不能删除");
        }
        //判断是否有音频文件
        int audioCount = audioMapper.getAudioCount(id);
        if(audioCount>0){
            return Result.error(FailResultEnum.AUDIO_FOLDER_ERROR, "音频库文件夹中有音频，不能删除");
        }

//        //逻辑删除，更新delete_status状态
//        audioFolder.setDeleteStatus(NewsConstant.DELETE_STATUS_DELETE);
//        audioFolder.setUpdateTime(new Date(System.currentTimeMillis()));
//        int deleteCount = audioFolderMapper.updateDeleteStatus(audioFolder);
        //物理删除
        int deleteCount = audioFolderMapper.deleteByPrimaryKey(id);
        if(deleteCount>0){
            //判断父文件夹下面还有没有状态正常的子文件夹
            Integer superId = audioFolder.getSuperId();
            int siblingCount = audioFolderMapper.getSubfolderCount(superId);
            if(siblingCount==0){
                AudioFolder parent = new AudioFolder();
                parent.setId(superId);
                parent.setHasSubfolder(0);
                parent.setUpdateTime(new Date(System.currentTimeMillis()));
                int pCount = audioFolderMapper.updateHasSubfolder(parent);
                log.info("更新音频库父文件夹id={}的hasSubfolder状态为0,更新结果为{}", superId, pCount);
            }
            return Result.success(SuccessResultEnum.SUCCESS, "删除音频库文件夹成功");
        }else{
            return Result.success(SuccessResultEnum.SUCCESS, "删除音频库文件夹失败");
        }
    }

    public AudioFolder getAudioFolder(Integer id){
        return audioFolderMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据关键词分页查询音频
     * @param folderId
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<Audio> queryAudioIncludingSubfolders(Integer folderId, String keyword, Integer pageNum, Integer pageSize){
        AudioFolder audioFolder = getAudioFolder(folderId);
        String path = audioFolder.getPath();
        Page<?> page = PageHelper.startPage(pageNum, pageSize);
        List<Audio> audioList = audioMapper.queryAudioByPath(path, keyword);
        //设置音频文件的所在目录名称（全路径）
        for(Audio audio:audioList){
            Integer audioFolderId = audio.getFolderId();
            AudioFolder item = getAudioFolder(audioFolderId);
            String itemPath = item.getPath();
            String[] array = itemPath.split("/");
            StringBuffer stringBuffer = new StringBuffer();
            for(int i=1; i<array.length; i++){
                Integer subAudioFolderId = Integer.parseInt(array[i]);
                AudioFolder subItem = getAudioFolder(subAudioFolderId);
                if(i<array.length-1){
                    stringBuffer.append(subItem.getFolderName()).append("/");
                }else{
                    stringBuffer.append(subItem.getFolderName());
                }
            }
            audio.setFullFolderName(stringBuffer.toString());
        }
        PageInfo<Audio> audioPageInfo = new PageInfo<>(audioList);
        return audioPageInfo;
    }


    /**
     * 根据关键词查询：支持高级搜索
     * @param audioQueryParam
     * @param user
     * @return
     */
    public PageInfo<Audio> queryAudioIncludingSubfolders(AudioQueryParam audioQueryParam, Users user){
        Integer folderId = audioQueryParam.getFolderId();
        if(folderId!=null){
            AudioFolder audioFolder = audioFolderMapper.selectByPrimaryKey(folderId);
            String path = audioFolder.getPath();
            audioQueryParam.setPath(path);
        }
        Integer audioType = audioQueryParam.getAudioType();
        if(audioType!=null){
            String strAudioType = null;
            if(audioType == AudioEnum.AUDIO_MP3.getType()){
                strAudioType=AudioEnum.AUDIO_MP3.getNote();
            }else if(audioType ==AudioEnum.AUDIO_WAV.getType()){
                strAudioType=AudioEnum.AUDIO_WAV.getNote();
            }
            audioQueryParam.setStrAudioType(strAudioType);
        }
        if(audioQueryParam.getOnlyMine()!=null && audioQueryParam.getOnlyMine()==1){//只看自己
            audioQueryParam.setUploadUserId(user.getUserid());
        }
        if(audioQueryParam.getDeleteStatus()==null){
            audioQueryParam.setDeleteStatus(0);
        }
        Long intKeyword = null;
        try{
            intKeyword = Long.parseLong(audioQueryParam.getKeyword());
            audioQueryParam.setIntKeyword(intKeyword);
        }catch(Exception e){
            //log.error(e.getMessage(), e);
        }
        Page<?> page = PageHelper.startPage(audioQueryParam.getPageNum(), audioQueryParam.getPageSize());
        List<Audio> audioList = audioMapper.advancedQueryAudioByPath(audioQueryParam);

        //设置音频文件的所在目录名称（全路径）
        buildFullFolderName(audioList);

        PageInfo<Audio> audioPageInfo = new PageInfo<>(audioList);
        return audioPageInfo;
    }


    private void buildFullFolderName(List<Audio> audioList){
        for(Audio audio:audioList){
            Integer audioFolderId = audio.getFolderId();
            AudioFolder item = getAudioFolder(audioFolderId);
            String itemPath = item.getPath();
            String[] array = itemPath.split("/");
            StringBuffer stringBuffer = new StringBuffer();
            for(int i=1; i<array.length; i++){
                Integer subAudioFolderId = Integer.parseInt(array[i]);
                AudioFolder subItem = getAudioFolder(subAudioFolderId);
                if(i<array.length-1){
                    stringBuffer.append(subItem.getFolderName()).append("/");
                }else{
                    stringBuffer.append(subItem.getFolderName());
                }
            }
            audio.setFullFolderName(stringBuffer.toString());
        }
    }

    /**
     * 音频文件上传，支持多文件
     * @param files
     * @param audioNotes
     * @param folderId
     * @param audioSource
     * @param audioEditor
     * @param userId
     * @return
     */
    public Result uploadAudio(MultipartFile[] files, String[] audioNotes, Integer folderId, String audioSource, String audioEditor, String userId){
        AudioFolder audioFolder = null;
        if(folderId==null){
            audioFolder = audioFolderMapper.getDefaultAudioFolder();
        }else{
            audioFolder = getAudioFolder(folderId);
        }
        if(audioFolder==null){
            return Result.error("音频文件夹id错误，没有这个音频文件夹或者没有默认音频文件夹");
        }
        String path = audioFolder.getPath();
        int index = path.indexOf("/");
        String vFolder = NewsConstant.AUDIO_ROOT+path.substring(index);
        log.info("上传音频文件到oss的目录={}", vFolder);
        //多文件上传
        int failCount = 0;
        int successCount = 0;
        int fileCount = files.length;
        if(fileCount==1 && audioNotes.length==0){
            audioNotes = new String[1];
            audioNotes[0] = "";
        }
        StringBuffer sb = new StringBuffer("第");
        for(int i=0; i<files.length; i++){
            MultipartFile file = files[i];
            String audioNote = audioNotes[i];
            log.info("上传音频audioNote={}, i={}", audioNote, i);
            String fileUrl = ossComponent.uploadToOSS(file, vFolder);
            if(fileUrl!=null&&fileUrl.length()>0) {
                long timestamp = System.currentTimeMillis();
                Date currentDate = new Date(timestamp);
                Audio audio = new Audio();
                audio.setCreateTime(currentDate);
                audio.setFolderId(audioFolder.getId());
                audio.setUploadUserId(userId);
                audio.setUpdateTime(currentDate);
                audio.setUpdateUserId(userId);
                audio.setAudioNote(audioNote);
                audio.setAudioSource(audioSource);
                audio.setAudioEditor(audioEditor);

                //计算音频文件时长
                File tempFile = null;
                try{
                    tempFile = FileUtil.multipartFileToFile(file);
                    MultimediaObject instance = new MultimediaObject(tempFile);
                    MultimediaInfo result = instance.getInfo();
                    long ls = result.getDuration()/1000;
                    audio.setAudioDuration(new Long(ls).intValue());
                }catch(Exception e){
                    log.error(e.getMessage(), e);
                    audio.setAudioDuration(0);
                }finally {
                    if(tempFile!=null) {
                        //清除临时文件
                        FileUtil.deleteTempFile(tempFile);
                    }
                }

                audio.setAudioFormat(file.getContentType());
                //audio.setAudioIsUse(0);
                audio.setAudioLength(new Long(file.getSize()).intValue()/(1024));
                audio.setAudioName(file.getOriginalFilename());
                audio.setAudioUrl(fileUrl);

                int count = saveAudio(audio);
                if(count==1){
                    successCount++;
                }else{
                    failCount++;
                    sb.append((i+1)).append("、");
                }
            }else{
                failCount++;
            }
        }
        if(failCount==0){//全部成功
            return Result.success("音频上传成功");
        }else if(successCount==0){//全部失败
            return Result.error(failCount+"个音频上传全部失败", failCount+"个音频上传全部失败");
        }else{//部分成功、部分失败
            sb.deleteCharAt(sb.length() - 1);//删除最后一个字符
            return Result.custom(400,failCount+"个（"+sb.toString()+")音频上传失败,"+successCount+"个音频上传成功",failCount+"个（"+sb.toString()+")音频上传失败,"+successCount+"个音频上传成功");
        }
    }

    public int saveAudio(Audio audio){
        return audioMapper.insertSelective(audio);
    }

    public Result updateAudio(AudioParam audioParam, Users user){
        Audio audio = new Audio();
        audio.setId(audioParam.getId());
        audio.setAudioName(audioParam.getAudioName());
        audio.setAudioNote(audioParam.getAudioNote());
        audio.setAudioSource(audioParam.getAudioSource());
        audio.setAudioEditor(audioParam.getAudioEditor());
        audio.setFolderId(audioParam.getFolderId());
        audio.setUpdateTime(new Date(System.currentTimeMillis()));
        audio.setUpdateUserId(user.getUserid());
        int count = audioMapper.updateAudio(audio);
        if(count>0){
            return Result.success("修改音频属性成功");
        }else{
            return Result.error("修改音频属性失败");
        }
    }

    /**
     * 更新音频名称
     * @param id
     * @param newAudioName
     * @param userId
     * @return
     */
    public Result updateAudioName(Integer id, String newAudioName, String userId){
        Audio audio = new Audio();
        audio.setId(id);
        audio.setAudioName(newAudioName);
        audio.setUpdateTime(new Date(System.currentTimeMillis()));
        audio.setUpdateUserId(userId);
        int count = audioMapper.updateAudio(audio);
        if(count>0){
            return Result.success("修改音频名称成功");
        }else{
            return Result.error("修改音频名称失败");
        }
    }

    /**
     * 更新音频备注
     * @param id
     * @param newAudioNote
     * @param userId
     * @return
     */
    public Result updateAudioNote(Integer id, String newAudioNote, String userId){
        Audio audio = new Audio();
        audio.setId(id);
        audio.setAudioNote(newAudioNote);
        audio.setUpdateTime(new Date(System.currentTimeMillis()));
        audio.setUpdateUserId(userId);
        int count = audioMapper.updateAudio(audio);
        if(count>0){
            return Result.success("修改音频备注成功");
        }else{
            return Result.error("修改音频备注失败");
        }
    }

    /**
     * 更新音频来源
     * @param id
     * @param newAudioSource
     * @param userId
     * @return
     */
    public Result updateAudioSource(Integer id, String newAudioSource, String userId){
        Audio audio = new Audio();
        audio.setId(id);
        audio.setAudioSource(newAudioSource);
        audio.setUpdateTime(new Date(System.currentTimeMillis()));
        audio.setUpdateUserId(userId);
        int count = audioMapper.updateAudio(audio);
        if(count>0){
            return Result.success("修改音频来源成功");
        }else{
            return Result.error("修改音频来源失败");
        }
    }

    /**
     * 更新音频编辑
     * @param id
     * @param newAudioEditor
     * @param userId
     * @return
     */
    public Result updateAudioEditor(Integer id, String newAudioEditor, String userId){
        Audio audio = new Audio();
        audio.setId(id);
        audio.setAudioEditor(newAudioEditor);
        audio.setUpdateTime(new Date(System.currentTimeMillis()));
        audio.setUpdateUserId(userId);
        int count = audioMapper.updateAudio(audio);
        if(count>0){
            return Result.success("修改音频编辑成功");
        }else{
            return Result.error("修改音频编辑失败");
        }
    }

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Throwable.class)
    public Result deleteAudio2Recycle(Integer id) {
        Audio dbAudio = audioMapper.selectByPrimaryKey(id);
        if(dbAudio==null) {
            return Result.error("没有该音频");
        }
        if(dbAudio.getUseCount()>0) {
            return Result.error("该音频被使用，不能删除");
        }
        Audio audio = new Audio();
        audio.setId(id);
        audio.setDeleteStatus(1);
        Date currentTime = new Date(System.currentTimeMillis());
        audio.setUpdateTime(currentTime);
        audio.setRecycleTime(currentTime);
        int count = audioMapper.updateAudio(audio);
        if(count>0) {
            return Result.success("删除音频到回收站成功");
        }else {
            return Result.error("删除音频到回收站失败");
        }
    }

    /**
     * 删除音频到回收站，实际是更新音频的deleteStatus状态值
     * @param ids
     * @return
     */
    public Result deleteAudio2Recycle(Integer[] ids){
        int failCount = 0;
        int successCount = 0;
        AudioService proxy = (AudioService)AopContext.currentProxy();
        for(Integer id:ids) {
            try {
                Result result = proxy.deleteAudio2Recycle(id);
                if(result.getStatus().intValue()==200) {
                    successCount++;
                }else{
                    failCount++;
                }
            }catch(Exception e) {
                log.error(e.getMessage(), e);
                failCount++;
            }
        }
        if(failCount==0){
            return Result.success("删除"+successCount+"个音频到回收站成功");
        }else if(successCount==0){
            return Result.error("删除"+successCount+"个音频到回收站失败，原因可能是音频被使用", "删除"+successCount+"个音频到回收站失败，原因可能是音频被使用");
        }else{
            return Result.custom(400, failCount+"个音频删除到回收站失败,原因可能是音频被使用"+successCount+"个音频删除到回收站成功", failCount+"个音频删除到回收站失败,"+successCount+"个音频删除到回收站成功");
        }
    }

//    public Result updateAudioIsUse(Integer id, Integer newAudioIsUse, String userId){
//        Audio oldAudio = audioMapper.selectByPrimaryKey(id);
//        if(oldAudio.getAudioIsUse().intValue()==newAudioIsUse.intValue()){
//            log.info("音频使用状态相同，无需更新，音频id={}，原使用状态={}，新使用状态={}", id, oldAudio.getAudioIsUse(), newAudioIsUse);
//            return Result.success("音频使用状态无需更新");
//        }
//        Audio audio = new Audio();
//        audio.setId(id);
//        audio.setAudioIsUse(newAudioIsUse);
//        audio.setUpdateTime(new Date(System.currentTimeMillis()));
//        audio.setUpdateUserId(userId);
//        int count = audioMapper.updateAudio(audio);
//        if(count>0){
//            return Result.success("更新音频使用状态成功");
//        }else{
//            return Result.error("更新音频使用状态失败");
//        }
//    }

    public Result getAudioTotalSize(){
        Long totalSize = audioMapper.getAudioTotalSize();
        if(totalSize==null){
            totalSize=0L;
        }
        return Result.success(totalSize);
    }

    /**
     * 更新音频最后使用时间及使用次数
     * @param audioUseParam
     * @return
     */
    public Result useAudio(AudioUseParam audioUseParam){
        Date currentTime = new Date(System.currentTimeMillis());
        audioUseParam.setLastUseTime(currentTime);
        int count = audioMapper.updateAudioUse(audioUseParam);
        if(count>0){
            return Result.success("更新音频使用时间、使用次数成功");
        }else{
            return Result.error("更新音频使用时间、使用次数失败");
        }
    }

    /**
     * 设置音频库默认文件夹
     * @param audioFolderParam
     * @return
     */
    public Result updateAudioDefaultFolder(AudioFolderParam audioFolderParam){
        //先清除原有默认文件夹设置
        int count = audioFolderMapper.clearDefaultFolder();
        int count2 = audioFolderMapper.setDefaultFolder(audioFolderParam.getId());
        if(count2>0){
            return Result.success("更新音频库默认文件夹成功");
        }else{
            return Result.success("更新音频库默认文件夹失败");
        }
    }

    public Result moveAudio(Integer[] ids, Integer targetFolderId){
        int failCount = 0;//文件移动失败数量
        int successCount = 0;//文件移动成功数量
        AudioService proxy = (AudioService) AopContext.currentProxy();
        for(Integer id:ids){
            //int count = movePicture(id, targetFolderId);
            int count = 0;
            try{
                count = proxy.moveAudio(id, targetFolderId);
            }catch(Exception e){
                log.error(e.getMessage(), e);
            }
            if(count>0){
                successCount ++;
            }else{
                failCount ++;
            }
        }
        if(failCount==0){
            return Result.success("移动音频成功");
        }else{
            return Result.success(failCount+"个音频移动失败,"+successCount+"个音频移动成功");
        }
    }

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Throwable.class)
    public int moveAudio(Integer id, Integer targetFolderId){
        Audio audio = new Audio();
        audio.setId(id);
        audio.setFolderId(targetFolderId);
        int count = audioMapper.updateAudio(audio);
        return count;
    }

    /**
     * 回收站中查询音频
     * @param audioRecycleQueryParam
     * @return
     */
    public PageInfo<Audio> queryAudioInRecycle(AudioRecycleQueryParam audioRecycleQueryParam){
        Integer audioType = audioRecycleQueryParam.getAudioType();
        if(audioType== AudioEnum.AUDIO_MP3.getType()){
            audioRecycleQueryParam.setStrAudioType(AudioEnum.AUDIO_MP3.getNote());
        }else if(audioRecycleQueryParam.getAudioType()==AudioEnum.AUDIO_WAV.getType()){
            audioRecycleQueryParam.setStrAudioType(AudioEnum.AUDIO_WAV.getNote());
        }
        Page<?> page = PageHelper.startPage(audioRecycleQueryParam.getPageNum(), audioRecycleQueryParam.getPageSize());
        List<Audio> audioList = audioMapper.queryAudioInRecycle(audioRecycleQueryParam);

        //设置音频文件的所在目录名称（全路径）
        buildFullFolderName(audioList);

        PageInfo<Audio> audioPageInfo = new PageInfo<>(audioList);
        return audioPageInfo;
    }

    public Result restoreAudio(Integer[] ids){
        int failCount = 0;
        int successCount = 0;
        AudioService proxy = (AudioService) AopContext.currentProxy();
        for(Integer id:ids){
            try{
                proxy.restoreAudio(id);
                successCount++;
            }catch (Exception e){
                log.error(e.getMessage(), e);
                failCount++;
            }
        }
        if(failCount==0){
            return Result.success("复原音频成功");
        }else{
            return Result.success(failCount+"个音频复原失败,"+successCount+"个音频复原成功");
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    public Result restoreAudio(Integer id){
        Audio audio = new Audio();
        audio.setId(id);
        audio.setDeleteStatus(0);
        audio.setUpdateTime(new Date(System.currentTimeMillis()));
        int count = audioMapper.updateAudio(audio);
        if(count>0){
            return Result.success("从回收站恢复音频成功");
        }else{
            return Result.error("从回收站恢复音频失败");
        }

    }

    public Result deleteAudioFromRecycle(Integer[] ids){
        int failCount = 0;
        int successCount = 0;
        AudioService proxy = (AudioService) AopContext.currentProxy();
        for(Integer id:ids){
            try{
                proxy.deleteAudioFromRecycle(id);
                successCount++;
            }catch(Exception e){
                log.error(e.getMessage(), e);
                failCount++;
            }
        }
        if(failCount==0){
            return Result.success("从回收站批量删除"+successCount+"成功");
        }else{
            return Result.success("从回收站删除"+failCount+"个音频失败,"+successCount+"个音频成功");
        }

    }

    @Transactional(rollbackFor = Throwable.class)
    public Result deleteAudioFromRecycle(Integer id){
        //首先查询
        Audio audio = audioMapper.selectByPrimaryKey(id);
        //其次删除数据库中该音频的记录
        if(audio==null){
            return Result.error("没有这个音频id="+id);
        }
        if(audio.getDeleteStatus()!=1){
            return Result.error("音频不在回收站中，不能彻底删除,id="+id);
        }
        int count = audioMapper.deleteByPrimaryKey(id);
//        int count = 1;
        if(count>0){
            //最后删除阿里云oss中该图片
            String audioUrl = audio.getAudioUrl();
            boolean b = ossComponent.deleteFromOSS(audioUrl);
            log.info("删除音频库音频{}结果{}", audioUrl, b);
            return Result.success("删除音频成功");
        }else{
            return Result.error("删除音频失败");
        }

    }

    /**
     * 清空音频回收站
     * @return
     */
    public Result clearRecycle(){
        //获取回收站所有的音频id
        List<Integer> ids = audioMapper.listAudioIdInRecycle();
        int failCount = 0;
        int successCount = 0;
        AudioService proxy = (AudioService) AopContext.currentProxy();
        for(Integer id:ids){
            try{
                proxy.deleteAudioFromRecycle(id);
                successCount++;
            }catch(Exception e){
                log.error(e.getMessage(), e);
                failCount++;
            }
        }
        if(failCount==0){
            return Result.success("清空回收站"+successCount+"个音频成功");
        }else{
            return Result.success("清空回收站"+failCount+"个音频失败,"+successCount+"个音频成功");
        }

    }
}
